﻿namespace _4_NovaAdmin.Web.Core.Idempotency;

public class IdempotencyStoreFactory : ISingletonDependency
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IdempotencyOptions _options;
    public IdempotencyStoreFactory(IServiceProvider serviceProvider, IOptions<IdempotencyOptions> options)
    {
        _serviceProvider = serviceProvider;
        _options = options.Value;
    }

    /// <summary>
    /// 根据配置选取存储的方式
    /// </summary>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    /// <exception cref="NotImplementedException"></exception>
    public IIdempotencyStore CreateStore()
    {
        return _options.StorageType switch
        {
            "Redis" => _serviceProvider.GetService<RedisIdempotencyStore>() ?? throw new InvalidOperationException("RedisIdempotencyStore is not registered."),
            "MemoryCache" => _serviceProvider.GetService<MemoryCacheIdempotencyStore>() ?? throw new InvalidOperationException("MemoryCacheIdempotencyStore is not registered."),
            "Database" => _serviceProvider.GetService<DatabaseIdempotencyStore>() ?? throw new InvalidOperationException("DatabaseIdempotencyStore is not registered."),
            _ => throw new NotImplementedException($"No implementation for {_options.StorageType}"),
        };
    }
}
